<template>
  <el-dialog :title="isNewRef ? '新建部门' : '编辑部门'" v-model="dialogVisible" width="30%" center>
    <div class="form">
      <el-form :model="formData" label-width="70">
        <el-form-item label="用户名" prop="name">
          <el-input v-model="formData.name" placeholder="请输入部门名称" />
        </el-form-item>

        <el-form-item label="部门领导" prop="leader">
          <el-input v-model="formData.leader" placeholder="请输入部门领导" />
        </el-form-item>

        <el-form-item label="上级领导" prop="parentId">
          <el-select v-model="formData.parentId" placeholder="请选择上级部门">
            <template v-for="dept in entireDepartments" :key="dept.id">
              <el-option :value="dept.id + ''" :label="dept.name" />
            </template>
          </el-select>
        </el-form-item>
      </el-form>
    </div>

    <template #footer>
      <span>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirm">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
  import { reactive, ref } from 'vue'
  import { storeToRefs } from 'pinia'
  import useSystemStore from '@/store/main/system/system'
  import useMainStore from '@/store/main/main'

  const dialogVisible = ref<boolean>(false)
  const isNewRef = ref<boolean>(false)
  const editData = ref<any>(null)
  const formData = reactive<any>({
    name: '',
    leader: '',
    parentId: ''
  })
  const systemStore = useSystemStore()
  const mainStore = useMainStore()
  const { entireDepartments } = storeToRefs(mainStore)

  function setDialogVisible(isNew: boolean = true, itemData?: any) {
    isNewRef.value = isNew
    if (!isNew && itemData) {
      for (const key in formData) {
        formData[key] = itemData[key] + ''
      }
      delete formData.password
      editData.value = itemData
    } else {
      for (const key in formData) {
        formData[key] = ''
      }
      editData.value = null
    }
    dialogVisible.value = true
  }
  function confirm() {
    if (isNewRef.value) {
      systemStore
        .newPageDataAction('department', formData)
        .then(() => ElMessage.success('新建部门成功'))
        .catch(() => ElMessage.warning('新建部门失败'))
        .finally(() => (dialogVisible.value = false))
    } else {
      systemStore
        .editPageDataAction('department', editData.value.id, formData)
        .then(() => ElMessage.success('更新部门成功'))
        .catch(() => ElMessage.warning('更新部门失败'))
        .finally(() => (dialogVisible.value = false))
    }
  }

  defineExpose({
    setDialogVisible
  })
</script>

<style lang="scss" scoped>
  .form {
    padding: 0 20px;
  }
</style>
